<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>0库存管理 - 虚拟仓系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <!-- 统一导航栏 -->
    {% include 'includes/navbar.html' %}

    <div class="container mt-4">
        <h3>供应商虚拟库存（VMI库存核心功能）</h3>
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="input-group">
                    <select id="supplierSelect" class="form-select">
                        <option value="">所有供应商</option>
                    </select>
                    <input type="text" id="prodSearch" class="form-control" placeholder="搜索商品名称">
                    <button id="searchBtn" class="btn btn-primary">搜索</button>
                </div>
            </div>
            <div class="col-md-6 text-end">
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#syncModal">同步虚拟库存</button>
                <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#orderModal">创建零库存订单</button>
            </div>
        </div>
        <div class="card">
            <div class="card-body">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>供应商</th>
                            <th>商品ID</th>
                            <th>名称</th>
                            <th>虚拟库存</th>
                            <th>补货阈值</th>
                            <th>状态</th>
                            <th>更新时间</th>
                        </tr>
                    </thead>
                    <tbody id="supplierTable"></tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 同步虚拟库存弹窗 -->
    <div class="modal fade" id="syncModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header"><h5 class="modal-title">同步供应商虚拟库存</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <form id="syncForm">
                        <div class="mb-3"><label>供应商</label>
                            <select class="form-select" name="supplier_id" required id="syncSupplierSelect"></select>
                        </div>
                        <div class="mb-3"><label>商品ID</label><input type="text" class="form-control" name="product_id" required></div>
                        <div class="mb-3"><label>商品名称</label><input type="text" class="form-control" name="product_name" required></div>
                        <div class="mb-3"><label>虚拟库存数量</label><input type="number" class="form-control" name="virtual_quantity" min="0" required></div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button id="submitSync" class="btn btn-primary">确认同步</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 创建零库存订单弹窗 -->
    <div class="modal fade" id="orderModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header"><h5 class="modal-title">创建零库存订单（供应商直发）</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <form id="orderForm">
                        <div class="mb-3"><label>供应商</label>
                            <select class="form-select" name="supplier_id" required id="orderSupplierSelect"></select>
                        </div>
                        <div class="mb-3"><label>商品ID</label><input type="text" class="form-control" name="product_id" required></div>
                        <div class="mb-3"><label>订单数量</label><input type="number" class="form-control" name="quantity" min="1" required></div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button id="submitOrder" class="btn btn-success">创建订单</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 加载供应商列表（带/api前缀）
        const loadSuppliers = async () => {
            const res = await fetch('/api/supplier/list');
            const suppliers = await res.json();
            const selectors = ['supplierSelect', 'syncSupplierSelect', 'orderSupplierSelect'];
            selectors.forEach(id => {
                const selector = document.getElementById(id);
                selector.innerHTML += suppliers.map(s => `<option value="${s.id}">${s.supplier_name}</option>`).join('');
            });
        };

        // 加载虚拟库存（带/api前缀）
        const loadSupplierInventory = async () => {
            const supplierId = document.getElementById('supplierSelect').value;
            const prodName = document.getElementById('prodSearch').value;
            const res = await fetch(`/api/supplier/inventory?supplier_id=${encodeURIComponent(supplierId)}&product_name=${encodeURIComponent(prodName)}`);
            const data = await res.json();
            const table = document.getElementById('supplierTable');
            table.innerHTML = data.map(item => `
                <tr>
                    <td>${item.supplier_name}</td>
                    <td>${item.product_id}</td>
                    <td>${item.product_name}</td>
                    <td>${item.virtual_quantity}</td>
                    <td>${item.threshold}</td>
                    <td><span class="badge ${item.status === '预警' ? 'bg-danger' : 'bg-success'}">${item.status}</span></td>
                    <td>${item.update_time}</td>
                </tr>
            `).join('');
        };

        // 同步虚拟库存（带/api前缀）
        document.getElementById('submitSync').addEventListener('click', async () => {
            const formData = Object.fromEntries(new FormData(document.getElementById('syncForm')));
            const res = await fetch('/api/supplier/inventory/sync', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(formData)
            });
            const data = await res.json();
            alert(data.message);
            if (data.status === 'success') {
                document.getElementById('syncForm').reset();
                document.querySelector('#syncModal .btn-close').click();
                loadSupplierInventory();
            }
        });

        // 创建零库存订单（带/api前缀）
        document.getElementById('submitOrder').addEventListener('click', async () => {
            const formData = Object.fromEntries(new FormData(document.getElementById('orderForm')));
            const res = await fetch('/api/order/zero-stock', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(formData)
            });
            const data = await res.json();
            alert(`${data.message}\n订单号：${data.order_id || ''}`);
            if (data.status === 'success') {
                document.getElementById('orderForm').reset();
                document.querySelector('#orderModal .btn-close').click();
                loadSupplierInventory();
            }
        });

        document.getElementById('searchBtn').addEventListener('click', loadSupplierInventory);
        document.getElementById('logout').addEventListener('click', () => window.location.href = '/login_page');
        window.onload = async () => {
            await loadSuppliers();
            loadSupplierInventory();
        };
    </script>
</body>
</html>